package com.heima.media.listener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @Author WSJ
 * @Date 2022-03-15-17:00
 * @Version 1.0 （版本号）
 */
@Service
public class PublishListener {
    @Autowired
    private RedissonClient client;

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IWmNewsService wmNewsService;

    @PostConstruct
    public void publish(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                RBlockingDeque<Object> rBlockingDeque = client.getBlockingDeque("article_publish");
                RDelayedQueue<Object> delayedQueue = client.getDelayedQueue(rBlockingDeque);
                delayedQueue.offerAsync("init",1, TimeUnit.MILLISECONDS);
                while (true){
                    try {
                        String poll = (String) rBlockingDeque.poll(10, TimeUnit.SECONDS);
                        if (poll!=null&&!"init".equals(poll)){
                            //执行发布任务
                            WmNews wmNews = JSON.parseObject(poll, WmNews.class);
                            auditService.audit(wmNews);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
